package com.juitar.base;

import java.io.Serializable;
import java.util.*;

/**
 * Class Tuning represents string instrument's tuning.
 * 
 * @author SKopylov
 *
 */

public class Tuning implements Serializable {
	private final int[] openStringNotes;

	private final String name;

	/**
	 * Creates string instrument tuning.
	 * Constructor is private, tunings could be created
	 * by using factory method
	 * @param name - tuning name 
	 * @param notes - array of open string notes 
	 * @see {@link Note}
	 */
	private Tuning(String name, int[] notes) {
		this.name = name;
		openStringNotes = notes;
	}

	public String toString() {
		return name;
	}

	public int[] getOpenStringNotes() {
		return openStringNotes;
	}

	public int strings() {
		return openStringNotes.length;
	}
	
	public String getName() {
		return name;
	}
	

	/**
	 * Factory method to create tunings. Tuning name = note, [note]
	 * @param tuning string in format "TuningName =  note, [note]"
	 * <br>Example of parameter - "Standard = 64,59,55,50,45,40"
	 */
	public static Tuning create(String tuning) {
		int pos = tuning.indexOf("=");
		if (pos >= 0) {
			String tuningName = tuning.substring(0, pos).trim();
			StringTokenizer t = new StringTokenizer(tuning.substring(pos + 1),
					",; \t\n\r\f");
			int[] notes = new int[t.countTokens()];
			for (int i = 0; i < notes.length; i++) {
				String stringNote = t.nextToken();
				notes[i] = Integer.decode(stringNote).intValue();// Note.toNote(stringNote);
			}
			return new Tuning(tuningName, notes);
		} else {
			throw new IllegalArgumentException("Bad tuning " + tuning);
		}
	}

	// Examples of tunings
	static private final int[] standard = { Note.E, Note.B, Note.G, Note.D,
			Note.A, Note.E };

	static public final Tuning STANDARD = new Tuning("Standard", standard);

	static private final int[] openG = { Note.D, Note.B, Note.G, Note.D,
			Note.G, Note.D };

	static public final Tuning OPEN_G = new Tuning("Open G", openG);

}